package com.cwj;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.Base64;
import java.util.Random;
import java.util.UUID;

/**
 * @author chenwujie
 * @date 2020/9/2213:38
 */
public class ImageBase64 {
    private static String randString = "0123456789ABCDEFGHIJLMNQRTY";// 随机生成字符串的取值范围
    private static int width = 80; // 图片宽度
    private static int height = 34; // 图片高度
    private static int StringNum = 4; // 字符的数量
    private static int lineSize = 0; // 干扰线数量

    // 将构造函数私有化 禁止new创建
    private ImageBase64() {
        super();
    }

    /**
     * 获取随机字符,并返回字符的String格式
     *
     * @param index (指定位置)
     * @return
     */
    private static String getRandomChar(int index) {
        // 获取指定位置index的字符，并转换成字符串表示形式
        return String.valueOf(randString.charAt(index));
    }

    /**
     * 获取随机指定区间的随机数
     *
     * @param min (指定最小数)
     * @param max (指定最大数)
     * @return
     */
    private static int getRandomNum(int min, int max) {
        Random random = new Random();
        return random.nextInt(max) % (max - min + 1) + min;
    }

    /**
     * 获得字体
     *
     * @return
     */
    private static Font getFont() {
        // 名称、样式、磅值
        return new Font("Fixedsys", Font.CENTER_BASELINE, 25);
    }

    /**
     * 获得颜色
     *
     * @param frontColor
     * @param backColor
     * @return
     */
    private static Color getRandColor(int frontColor, int backColor) {
        frontColor = frontColor > 255 ? 255 : frontColor;
        backColor = backColor > 255 ? 255 : backColor;

        // 随机类，用于生成随机参数
        Random random = new Random();
        int red = frontColor + random.nextInt(backColor - frontColor - 16);
        int green = frontColor + random.nextInt(backColor - frontColor - 14);
        int blue = frontColor + random.nextInt(backColor - frontColor - 18);
        return new Color(red, green, blue);
    }

    /**
     * 绘制字符串,返回绘制的字符串
     *
     * @param g
     * @param randomString
     * @param i
     * @return
     */
    private static String drawString(Graphics g, String randomString, int i) {
        Random random = new Random(); // 随机类，用于生成随机参
        Graphics2D g2d = (Graphics2D) g;
        g2d.setFont(getFont()); // 设置字体
        g2d.setColor(new Color(random.nextFloat(), random.nextFloat(), random.nextFloat()));// 设置颜色
        String randChar = String.valueOf(getRandomChar(random.nextInt(randString.length())));
        randomString += randChar; // 组装
        int rot = getRandomNum(5, 10);
        g2d.translate(random.nextInt(3), random.nextInt(3));
        g2d.rotate(rot * Math.PI / 180);
        g2d.drawString(randChar, 15 * (i-1) + 10, 20);
        g2d.rotate(-rot * Math.PI / 180);
        return randomString;
    }

    /**
     * 绘制干扰线
     *
     * @param g
     */
    private static void drawLine(Graphics g) {
        // 随机类，用于生成随机参
        Random random = new Random();
        // 起点(x,y) 偏移量x1、y1
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(13);
        int yl = random.nextInt(15);
        g.setColor(new Color(random.nextFloat(), random.nextFloat(), random.nextFloat()));
        g.drawLine(x, y, x + xl, y + yl);
    }

    /**
     * 生成Base64验证码，并放入到缓存中
     *
     * @return String 返回base64
     * @MethodName: getRandomCode
     */
    public static Validate getRandomCode() {
        Validate validate = new Validate();

        // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        // 获得BufferedImage对象的Graphics对象
        Graphics g = image.getGraphics();
        // 填充矩形
        g.fillRect(0, 0, width, height);
        // 设置字体
        g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));
        // 设置颜色
        g.setColor(getRandColor(110, 133));
        // 绘制干扰线
//        for (int i = 0; i <= lineSize; i++) {
//            drawLine(g);
//        }
        // 绘制字符
        String randomString = "";
        for (int i = 1; i <= StringNum; i++) {
            randomString = drawString(g, randomString, i);
        }
        System.out.println(randomString);
        String key = UUID.randomUUID().toString().replace("-", "");
        validate.setKey(key);
        validate.setValue(randomString.toLowerCase());
        //将生成的随机uuid和验证码值放入缓存中
        g.dispose();// 释放绘图资源
        ByteArrayOutputStream bs = null;
        try {
            bs = new ByteArrayOutputStream();
            // 转码成字符串
            // 将绘制得图片输出到流
            ImageIO.write(image, "jpeg", bs);
            byte[] captcha = bs.toByteArray();
            StringBuffer sb = new StringBuffer();
            String imgSrc = sb.append("data:image/jpeg;base64,").append(Base64.getEncoder().encodeToString(captcha)).toString();
            // 返回Base64编码过的字节数组字符串
            validate.setBase64Str(imgSrc);
        } catch (Exception e) {
        } finally {
            try {
                bs.close();
            } catch (IOException e) {
            } finally {
                bs = null;
            }
        }
        return validate;
    }


    /**
     * @ClassName: Validate
     * @Description: 验证码类
     */
    public static class Validate implements Serializable {
        private static final long serialVersionUID = 6371868703348755377L;
        /**
         * Base64 值
         */
        private String base64Str;
        /**
         * 验证码值
         */
        private String value;
        /**
         * 随机生成的UUID
         */
        private String key;

        public String getBase64Str() {
            return base64Str;
        }

        public void setBase64Str(String base64Str) {
            this.base64Str = base64Str;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }
    }

    public static void main(String[] args) {
        Validate randomCode = getRandomCode();
        System.out.println(randomCode.base64Str);
    }
}
